package com.cn.lp;

import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

/**
 * @author YuanZhiWei
 * 类说明：分布式锁的延时类
 * 该类实现了runnable，所以无法交给spring容器管理，即无法通过依赖注入来使用该类
 */
public class SurvivalClamProcessor implements Runnable {
    private final Logger log = LoggerFactory.getLogger(this.getClass());


    private static final int REDIS_EXPIRE_SUCCESS = 1;

    /**
     *
     * @param rLock
     * @param key
     * @param threadId 线程ID
     * @param lockTime
     */
    public SurvivalClamProcessor(RLock rLock,String key, String threadId, int lockTime) {
        this.rLock = rLock;
        this.key = key;
        this.threadId = threadId;
        this.lockTime = lockTime;
        this.signal = Boolean.TRUE;
    }

    private RLock rLock;

    private String key;

    private String threadId;

    private int lockTime;

    //线程关闭的标记
    private volatile Boolean signal;

    public void stop() {
        this.signal = Boolean.FALSE;
    }

    @Override
    public void run() {
        int waitTime = lockTime * 1000 * 2 / 3; //锁时间的三分之二 时续命
        while (signal) {
            try {
                Thread.sleep(waitTime);
                System.out.println(Thread.currentThread().getName());
                //此处如果不适用tryLockAsync会导致锁id进行变更。导致释放锁的时候报错。其中value的值的业务线程的id
                //异步尝试加锁，等待时间var1，锁超时时间var3，时间单位var5，var6为线程id
                if (rLock.tryLockAsync(lockTime,30,TimeUnit.SECONDS, Long.parseLong(threadId)).get()) {
                    if (log.isInfoEnabled()) {
                        log.info("expandLockTime 成功，本次等待{}ms，将重置锁超时时间重置为{}s,,key为{},threadId为{}",
                                waitTime, lockTime, key, Long.parseLong(threadId));
                    }
                } else {
                    if (log.isInfoEnabled()) {
                        log.info("expandLockTime 失败，将导致SurvivalClamConsumer中断");
                    }
                    this.stop();
                }
            } catch (InterruptedException e) {
                if (log.isInfoEnabled()) {
                    log.info("SurvivalClamProcessor 处理线程被强制中断");
                }
            } catch (Exception e) {
                log.error("SurvivalClamProcessor run error", e);
            }
        }

        if (log.isInfoEnabled()) {
            log.info("SurvivalClamProcessor 处理线程已停止");
        }
    }
}


